from django.shortcuts import render
from rest_framework import request
from rest_framework.generics import CreateAPIView
# Create your views here.
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from django_redis import get_redis_connection
# 生成订单的视图
from order.models import Order
from order.serializers import OrderModelSerializer


class OrderAPIView(CreateAPIView):
    queryset = Order.objects.all()
    serializer_class = OrderModelSerializer


# 在点击支付按钮后,将已付款的商品从购物车里面删除
class Orderdelete(ViewSet):
    def order_delete(self, request):
        user_id = request.user.id
        course_id = request.data.get("course_id")  # 获取商品id
        print("提交订单时获取到的商品id")
        print(course_id)
        if course_id:
            # 如果状态为选中,将商品从购物车中删除
            # //连接库.待会改
            redis_connection = get_redis_connection("cart")
            # 数据保存至redis中
            pipeline = redis_connection.pipeline()
            # 开启管道
            pipeline.multi()
            # 删除指定信息
            pipeline.hdel("cart_%s" % user_id, course_id)
            # 执行命令,开始删除,不执行不删除(懒加载)
            pipeline.execute()
            return Response({"message": "结算成功"})
        else:
            # 如果没有选中,返回提示信息,请先选中再删除
            return Response({"message": "结算失败"})


"""
def post(self, request, *args, **kwargs):
    # 开启事务
    with transaction.atomic():
        print("1111")
        # 记录事务的回滚点
        savepoint = transaction.savepoint()

        # 遇到异常  可以回到上一事务开启的点
        transaction.savepoint_rollback(savepoint)
"""
